<script lang="ts">
import { defineComponent, type PropType } from "vue";

export default defineComponent({
  props: {
    modelValue: { type: [Number, Array, String], required: true },
    mode: {
      type: String as PropType<"selector" | "multiSelector" | "date" | "time">,
      default: "selector",
    },
    range: Array,
    rangeKey: String,

    start: String,
    end: String,
    fields: {
      type: String as PropType<"year" | "month" | "day">,
      default: "day",
    },
  },
  emits: {
    "update:modelValue": (value: number | string) => {
      return typeof value === "number" || typeof value === "string";
    },
    change: (value: number | string) => {
      return typeof value === "number" || typeof value === "string";
    },
  },
  setup(props, ctx) {
    return {
      pickerChange: (e: MiniApp.Event<{ value: string }>) => {
        if (props.mode === "date" || props.mode === "time") {
          ctx.emit("update:modelValue", e.detail.value);
          ctx.emit("change", e.detail.value);
        } else {
          const value = e.detail.value;
          if (value === "") return;
          ctx.emit("update:modelValue", Number(value));
          ctx.emit("change", Number(value));
        }
      },
    };
  },
});
</script>

<template>
  <picker
    v-if="mode === 'date' || mode === 'time'"
    :mode="mode"
    :value="fields === 'day' ? modelValue : `${modelValue}-01`"
    :start="start"
    :end="end"
    :fields="fields"
    @change="pickerChange"
  >
    <slot />
  </picker>
  <picker
    v-else
    :mode="mode"
    :value="modelValue"
    :range="range"
    :rangeKey="rangeKey"
    @change="pickerChange"
  >
    <slot />
  </picker>
</template>
